package com.example.rotatewindow

import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import kotlinx.android.synthetic.main.activity_main.*
import java.util.stream.IntStream
import java.util.stream.Stream

class MainActivity : AppCompatActivity() {

    var windowView: View? = null
    var count = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv.setOnClickListener {
            if (windowView == null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!Settings.canDrawOverlays(getApplicationContext())) {
                        //启动Activity让用户授权
                        var intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                        intent.setData(Uri.parse("package:" + getPackageName()))
                        startActivityForResult(intent, 100)
                    } else {
                        show(tv)
                    }
                }
            } else {
                //totate
            }
            oldWay()
            newWay()
        }
    }

    private fun oldWay() {
        val nums = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 101)
        val timeStamp = System.nanoTime()
        var sum = 0
        for (i in nums) {
            sum += i
        }
        println("oldWay结果为：$sum")
        println("耗时：" + (System.nanoTime() - timeStamp))
    }

    @RequiresApi(Build.VERSION_CODES.N)
    private fun newWay() {
        val timeStamp = System.nanoTime()
        var sum = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 101).parallel().sum()
        println("newWay：$sum")
        println("耗时：" + (System.nanoTime() - timeStamp))
    }

    override fun onResume() {
        super.onResume()
    }

    private fun show(view: View?) {
        val wManager = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val wmParams = WindowManager.LayoutParams()
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
        }
        if (null != view) {
            wmParams.token = view!!.getWindowToken()
        }
        wmParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND
        wmParams.format = PixelFormat.RGBA_8888
        wmParams.gravity = Gravity.LEFT or Gravity.TOP
        wmParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
        wmParams.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
        wmParams.horizontalMargin = 0f
        wmParams.verticalMargin = 0f
        wmParams.horizontalWeight = 0f
        wmParams.verticalWeight = 0f
        wmParams.dimAmount = 0.1f
        wmParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        wmParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
        wmParams.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        wmParams.alpha = 1f
        wmParams.x = 0
        wmParams.y = 300
        wmParams.windowAnimations = android.R.anim.fade_in
        var tv = TextView(applicationContext)
        tv.setPadding(10, 10, 10, 10)
        tv.setText("悬浮窗口")
        tv.textSize = 30f
        tv.setBackgroundColor(Color.BLUE)
        tv.setOnClickListener(object : View.OnClickListener {
            override fun onClick(view: View) {
//                wManager.removeView(tv)
                windowView?.rotation = 90f * (count++)
                var param = windowView?.layoutParams
                var temp = param?.width
                param?.width = param?.height
                param?.height = temp
            }
        })
        tv.setOnTouchListener(object : View.OnTouchListener {

            override fun onTouch(v: View, event: MotionEvent): Boolean {
                wmParams.x = event.rawX.toInt() - tv.measuredWidth / 2
                wmParams.y = event.rawY.toInt() - tv.measuredHeight / 2
                wManager.updateViewLayout(tv, wmParams)
                return false
            }
        })
        windowView = tv
        wManager.addView(tv, wmParams)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    show(tv)
                } else {
                    Toast.makeText(
                        this,
                        "ACTION_MANAGE_OVERLAY_PERMISSION权限已被拒绝",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }

    override fun onPause() {
        windowView.apply {
            val wManager = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            wManager.removeViewImmediate(windowView)
        }
        super.onPause()
    }
}
